// EEPROM I2C控制器模块
module eeprom_i2c_ctrl # (
    parameter       SLAVE_ADDR = 7'b1010_000                //EEPROM从机地址
)
(
    input                                   clk_50m,
    input                                   rst_n,
    input                                   pb_flag,
(* MARK_DEBUG="true" *)output   reg [1:0]   cmd,            //00-none，2'b01-wr，2'b10-rd，11-no
(* MARK_DEBUG="true" *)output   reg [7:0]   wr_data,
(* MARK_DEBUG="true" *)output   reg [15:0]  addr,
    output                          [6:0]   device_addr,
    output                      reg         led,
    input                                   done,
    input                           [7:0]   rd_data
);
    
//===============================================
(* MARK_DEBUG="true" *)reg     [7:0]       wr_st; 
reg     [7:0]       rd_data_r;

reg     [24:0]      led_delay_cnt;          //500ms-2HZ
reg     [31:0]      wr_delay_cnt;       //delay_write

assign  device_addr =  SLAVE_ADDR;
//==============================================
//st
always @ (posedge clk_50m)
if(!rst_n)
begin
    wr_st <= 0;
    
    cmd <= 0;
    wr_data <= 0;
    addr <= 0;
    rd_data_r <= 0;
    
    led <= 1;
    led_delay_cnt <= 0;
    wr_delay_cnt <= 0;
end
else
begin
case(wr_st)
0:
begin
    if(pb_flag)
        wr_st <= 1;
    else
    begin
        wr_st <= 0;
        cmd <= 0;
        wr_data <= 0;
        addr <= 0;  
        rd_data_r <= 0;
    end
end
//=============================================
//wr
1:
begin
    if(done)
    begin
        wr_st <= 2;
        cmd <= 2'b00;
    end
    else
    begin
        cmd <= 2'b01;               //wr
        wr_data <= addr[7:0];
        addr <= addr;
    end
end

2:
begin
    if(wr_delay_cnt == 32'd500_000)         //10ms
    begin
        wr_delay_cnt <= 0;
        wr_st <= 3;
    end
    else
        wr_delay_cnt <= wr_delay_cnt + 1;
end

3:
begin
    if(addr < 16'd255)
    begin
        addr <= addr +1;
        wr_st <= 1;
    end
    else
    begin
        cmd <= 0;
        wr_data <= 0;
        addr <= 0;
        wr_st <= 4;
    end
end

//======================================
//rd
4:
begin
    led <= 0;
    if(pb_flag)
        wr_st <= 5;
end

5:
begin
    if(done)
    begin
        cmd <= 0;
        rd_data_r <= rd_data;
        wr_st <= 6;
    end
    else
    begin
        cmd <= 2'b10;
        addr <= addr;
    end
end

6:
begin
    if(rd_data_r == addr)
    begin
        if(addr < 16'd255)
        begin
            addr <= addr +1;
            wr_st <= 5;
        end
        else
        begin
            cmd <= 0;
            wr_data <= 0;
            addr <= 0;
            wr_st <= 0;
            led <=1;    
        end
    end
    else
    begin
        if(led_delay_cnt >= 25'd25000_000)
        begin
            led_delay_cnt <= 0;
            led <= ~led;                                    //led glitter
        end
        else
            led_delay_cnt <= led_delay_cnt +1;
    end 
end

endcase
end 
endmodule